﻿using Dapr.Client;
using Net03_Dapr_Shared;
using System.Net.Http.Json;

/// <summary>
/// 状态管理
/// </summary>
//Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
//Console.OutputEncoding = Encoding.GetEncoding("GBK");

HttpClient client = DaprClient.CreateInvokeHttpClient(appId: "app2");
var input = new Input { X=2,Y=1 };

Console.WriteLine("first request...");
await InvokeAsync("add", "+");
await InvokeAsync("sub", "-");
await InvokeAsync("mul", "*");
await InvokeAsync("div", "/");

Console.WriteLine("second request...");
await InvokeAsync("add", "+");
await InvokeAsync("sub", "-");
await InvokeAsync("mul", "*");
await InvokeAsync("div", "/");

async Task InvokeAsync(string method, string @operator)
{
    if(method == "add" || method =="sub")
    {
        var a = new DaprClientBuilder().Build();
        await a.PublishEventAsync("pubsub", topicName: "clearresult", new[] {method});
        Console.WriteLine("clear add or sub result cache.");
    }
    Thread.Sleep(2000); // 休息一下看看数据会不会同步
    var response = await client.PostAsync(method, JsonContent.Create(input));
    var output  = await response.Content.ReadFromJsonAsync<Output>();
    Console.WriteLine($"{input.X} {@operator} {input.Y} = {output.Result} ({output.Timestamp})");
}
